package bar.dark.lee.alarm.sound;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import bar.dark.lee.alarm.R;
import bar.dark.lee.alarm.SuperActivity;
import bar.dark.lee.alarm.common.BDUtil;
import bar.dark.lee.alarm.query.DBQuery;

public class SoundFolderActivity extends SuperActivity
{
	private ListView listView;
	private View resultView;
	private TextView folderPath;
	
	private Button addButton;
	private Button cancelButton;
	
	private SoundFolderData data;
	private ArrayList<SoundFolderData> list = new ArrayList<SoundFolderData>();
	
	private String path = "";
	
	private MediaPlayer mp;
	private AudioManager am;
	
	private int maxVolum;
	private int streamType = AudioManager.STREAM_RING;
	
	private String filePath = "";
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.sound_folder_activity);
		
		setTitle(getResources().getString(R.string.soundFolder_title));
		setFindView();
		setClickListener();
		path = Environment.getExternalStorageDirectory() + "";
		new ShowDialog().execute(BDUtil.asyncFlag, 0);
		
		mp = new MediaPlayer();
		am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		maxVolum = am.getStreamMaxVolume(streamType);
		am.setStreamVolume(streamType, maxVolum, AudioManager.STREAM_RING);
	}

	@Override
	public void setFindView()
	{
		folderPath = (TextView) findViewById(R.id.soundFolderPath);
		listView = (ListView) findViewById(R.id.soundFolderListView);
		addButton = (Button) findViewById(R.id.soundFolderAddButton);
		cancelButton = (Button) findViewById(R.id.soundFolderCancelButton);
	}
	
	@Override
	public void onBackPressed()
	{
		super.onBackPressed();
		if (mp.isPlaying())
		{
			mp.stop();
			mp.reset();
		}
	}

	@Override
	public void setDataSetting()
	{
		data = null;
		
		data = query.getFolderData(path);
		
		data = query.getMp3Data(data, path);
		
		if (data != null)
		{
			list.add(data);
		}
	}
	
	private void setHighDataSetting()
	{
		data = list.get(list.size()-2);
		list.remove(list.size()-1);
		
		ArrayList<SoundFolderData> tempList = new ArrayList<SoundFolderData>();
		
		for (int i = 0; i < list.size(); i++)
		{
			tempList.add(list.get(i));
		}
		
		list = new ArrayList<SoundFolderData>();;
		
		for (int i = 0; i < tempList.size(); i++)
		{
			list.add(tempList.get(i));
		}
	}
	
	private void setSaveData()
	{
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("path", data.getFolderPath());
		sql.insert(superContext, map, "sound_location");
	}

	@Override
	public void setClickListener()
	{
		addButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (mp.isPlaying())
				{
					mp.stop();
					mp.reset();
				}
				
				new ShowDialog().execute(BDUtil.asyncFlag, 2);
			}
		});
		
		cancelButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				onBackPressed();
			}
		});
	}
	
	private OnItemClickListener onItemClickListener = new OnItemClickListener()
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
				long arg3)
		{
			ArrayList<SoundLowData> lowList = data.getLowFolders();
			SoundLowData lowData = lowList.get(pos);
			
			if (lowData.getFolderAndFile() == 0)
			{
				path = lowData.getFolderPath();
				new ShowDialog().execute(BDUtil.asyncFlag, 0);
			}
			else if (lowData.getFolderAndFile() == 2)
			{
				if (mp.isPlaying())
				{
					mp.stop();
					mp.reset();
				}
				
				if (list.size() < 2)
				{
					BDUtil.showDialog(superContext, "알림", "최상위 폴더 입니다.");
					return;
				}
				
				new ShowDialog().execute(BDUtil.asyncFlag, 1);
			}
			else if (lowData.getFolderAndFile() == 1)
			{
				mp.setAudioStreamType(streamType);
				
				if (mp.isPlaying())
				{
					if (filePath.equals(lowData.getFolderPath()))
					{
						mp.pause();
					}
					else
					{
						mp.stop();
						mp.reset();
						
						try
						{
							mp.setDataSource(lowData.getFolderPath());
							filePath = lowData.getFolderPath();
							mp.prepare();
						} catch (Exception e)
						{
							e.printStackTrace();
						}
						
						mp.start();
					}
				}
				else
				{
					if (filePath.equals(lowData.getFolderPath()))
					{
						mp.start();
					}
					else
					{
						try
						{
							mp.reset();
							mp.setDataSource(lowData.getFolderPath());
							filePath = lowData.getFolderPath();
							mp.prepare();
						} catch (Exception e)
						{
							e.printStackTrace();
						}
						
						mp.start();
					}
				}
			}
		}
	};
	
	private class soundFolderAdapter extends ArrayAdapter<SoundLowData>
	{
		private ArrayList<SoundLowData> lowList;
		
		public soundFolderAdapter(Context context, int textViewResourceId,
				List<SoundLowData> objects)
		{
			super(context, textViewResourceId, objects);
			this.lowList = (ArrayList<SoundLowData>) objects;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			View v = convertView;
			
			if (v == null)
			{
				v = getLayoutInflater().inflate(R.layout.list_item_sound_folder, null);
			}
			
			SoundLowData data = lowList.get(position);
			
			TextView tv = (TextView) v.findViewById(R.id.listSoundFolderTextView);
			
			if (data.getFolderAndFile() == 0)
			{
				tv.setText("/" + data.getFolderName());
			}
			else
			{
				tv.setText(data.getFolderName());
			}
			
			
			return v;
		}
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (BDUtil.btnEnable)
			{
				BDUtil.btnEnable = false;
				BDUtil.asyncFlag = -1;
				
				dialog = new ProgressDialog(SoundFolderActivity.this);
				dialog.setCancelable(false);
				dialog.setMessage("Loading...");
				dialog.show();
			}
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			if (arg0[0] == 0)
			{
				if (arg0[1] == 0)
				{
					setDataSetting();
					return 0;
				}
				else if (arg0[1] == 1)
				{
					setHighDataSetting();
					return 0;
				}
				else if (arg0[1] == 2)
				{
					setSaveData();
					return 2;
				}
			}
			else
			{
				return arg0[0];
			}
			

			return -1;
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);

			if (dialog != null) {
				dialog.dismiss();
			}
			
			if (result == 0)
			{
				if (listView.getFooterViewsCount() > 0)
				{
					listView.removeFooterView(resultView);
				}
				
				if (list.size() < 1)
				{
					listView.addFooterView(resultView);
					listView.setFooterDividersEnabled(false);
				}
				else
				{
					listView.setOnItemClickListener(onItemClickListener);
					listView.setDividerHeight(1);
				}
				
				soundFolderAdapter adapter = new soundFolderAdapter(
						superContext, R.layout.list_item_sound_folder, data.getLowFolders());
				listView.setAdapter(adapter);
				adapter.notifyDataSetChanged();
				
				folderPath.setText(data.getFolderPath());
				
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
			}
			else if (result == 2)
			{
				BDUtil.showDialogFinish(superContext, "알림", "소리 폴더가 추가 되었습니다.");
			}
		}
	}

	@Override
	protected void tipButton()
	{
	}

}
